<template>
  <div class="single-room-timeline-page">
    <div class="header">
      <p><a href="#" @click.prevent="router.back()">&laquo; 返回概览</a></p>
      <h1>会议室详情与日程</h1>
    </div>

    <div v-if="loading" class="loading-message">加载中...</div>
    <div v-else-if="error" class="error-message">{{ error }}</div>
    <div v-else-if="!roomDetails" class="no-data-message">未找到会议室信息。</div>
    <div v-else>
      <div class="room-info">
        <h2>会议室 {{ roomDetails.roomname }} ({{ roomDetails.roomId }})</h2>
        <p><strong>容纳人数:</strong> {{ roomDetails.capacity }}人</p>
        <p><strong>设备:</strong>
          <span v-if="roomDetails.projector === 1">投影仪, </span>
          <span v-if="roomDetails.sound === 1">音响, </span>
          <span v-if="roomDetails.internet === 1">网络</span>
          <span v-if="roomDetails.projector === 0 && roomDetails.sound === 0 && roomDetails.internet === 0">无</span>
        </p>
        <p><strong>价格:</strong> {{ roomDetails.price }} 元/小时</p>
        <p><strong>面积:</strong> {{ roomDetails.area }} 平方米</p>
        <!-- Assuming operating hours are not part of roomDetails, or are fixed -->
        <p><strong>当前运营时段:</strong> 08:00 - 18:00</p>
      </div>


      <table class="schedule-table">
        <thead>
          <tr>
            <th>时间段</th>
            <th>状态 / 预定信息</th>
            <th>员工操作</th>
          </tr>
        </thead>
        <tbody>
          <RoomTimelineSlot
            v-for="(slot, index) in timeSlotsWithStatus"
            :key="index"
            :timeSlot="slot.time"
            :statusData="slot.status"
            @set-maintenance="handleSetMaintenance"
            @cancel-maintenance="handleCancelMaintenance"
            @set-in-use="handleSetInUse"
            @end-use="handleEndUse"
          />
          <tr v-if="timeSlotsWithStatus.length === 0">
            <td colspan="3" class="no-schedule-message">无排班信息。</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getRoomById, getRoomScheduleByDate, getRoomHourlyStatus } from '@/apis/room';
import RoomTimelineSlot from '@/components/rooms/RoomTimelineSlot.vue';

const route = useRoute();
const router = useRouter();
const roomId = computed(() => route.params.roomId);

const roomDetails = ref(null);
const scheduleData = ref([]); // Raw schedule data from API
const hourlyStatusData = ref([]); // Data from getRoomHourlyStatus API
const loading = ref(true);
const error = ref(null);


// Generate 30-minute time slots from 08:00 to 18:00
const timeSlotsWithStatus = computed(() => {
  // Map the hourlyStatusData to the format expected by RoomTimelineSlot
  return hourlyStatusData.value.map(item => {
    const startTime = new Date(item.startTime);
    const endTime = new Date(item.endTime);
    const timeSlot = `${String(startTime.getHours()).padStart(2, '0')}:${String(startTime.getMinutes()).padStart(2, '0')} - ${String(endTime.getHours()).padStart(2, '0')}:${String(endTime.getMinutes()).padStart(2, '0')}`;

    let status = { type: 'available' }; // Default to available

    switch (item.paymentStatus) {
      case 0: // 已预约未支付
        status.type = 'pending-payment';
        status.bookingInfo = {
          orderId: item.orderId,
          userId: item.userId,
          roomname: item.roomname,
          startTime: item.startTime,
          endTime: item.endTime,
          paymentStatus: item.paymentStatus
        };
        break;
      case 1: // 已支付未使用
        status.type = 'booked';
        status.bookingInfo = {
          orderId: item.orderId,
          userId: item.userId,
          roomname: item.roomname,
          startTime: item.startTime,
          endTime: item.endTime,
          paymentStatus: item.paymentStatus
        };
        break;
      case 5: // 已支付使用中
        status.type = 'in-use';
        status.bookingInfo = {
          orderId: item.orderId,
          userId: item.userId,
          roomname: item.roomname,
          startTime: item.startTime,
          endTime: item.endTime,
          paymentStatus: item.paymentStatus
        };
        break;
      case 6: // 空闲
        status.type = 'available';
        break;
      case 7: // 待维修和维修中
        status.type = 'maintenance';
        status.maintenanceInfo = {
          maintenanceId: item.maintenanceId,
          roomname: item.roomname,
          startTime: item.startTime,
          endTime: item.endTime,
          paymentStatus: item.paymentStatus
        };
        break;
      default:
        status.type = 'unknown';
        break;
    }
    return { time: timeSlot, status };
  });
});

const fetchRoomDetails = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await getRoomById(roomId.value);
    if (response.code === 200) {
      roomDetails.value = response.data;
    } else {
      error.value = response.msg || '获取会议室详情失败';
    }
  } catch (err) {
    error.value = '加载会议室详情时发生错误: ' + err.message;
    console.error('Error fetching room details:', err);
  } finally {
    loading.value = false;
  }
};

const fetchRoomSchedule = async () => {
  loading.value = true;
  error.value = null;
  try {
    // Use the new getRoomHourlyStatus API
    const response = await getRoomHourlyStatus(roomId.value);
    if (response.code === 200) {
      hourlyStatusData.value = response.data;
    } else {
      error.value = response.msg || '获取房间当日时间段状态失败';
    }
  } catch (err) {
    error.value = '加载房间当日时间段状态时发生错误: ' + err.message;
    console.error('Error fetching room hourly status:', err);
  } finally {
    loading.value = false;
  }
};


// Action handlers (placeholders for now)
const handleSetMaintenance = (timeSlot) => {
  alert(`设为维护: ${timeSlot}`);
  // Call API to set maintenance
};

const handleCancelMaintenance = (maintenanceInfo) => {
  alert(`解除维护: ${maintenanceInfo.reason}`);
  // Call API to cancel maintenance
};

const handleSetInUse = (bookingInfo) => {
  alert(`设为使用中: ${bookingInfo.title}`);
  // Call API to set booking in use
};

const handleEndUse = (bookingInfo) => {
  alert(`结束使用: ${bookingInfo.title}`);
  // Call API to end booking use
};

onMounted(() => {
  if (roomId.value) {
    fetchRoomDetails();
    fetchRoomSchedule(); // Fetch schedule without date
  } else {
    error.value = '未提供会议室ID。';
    loading.value = false;
  }
});

watch(roomId, (newId) => {
  if (newId) {
    fetchRoomDetails();
    fetchRoomSchedule(); // Fetch schedule without date
  }
});
</script>

<style scoped>
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f4f7f6; }
.header { margin-bottom: 20px; border-bottom: 1px solid #ddd; padding-bottom:10px; }
.header h1 { color: #333; margin-bottom: 5px;}
.header a { color: #007bff; text-decoration: none; }
.header a:hover { text-decoration: underline; }

.room-info { background-color: #e9ecef; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
.room-info h2 { margin-top: 0; color: #0056b3;}
.room-info p { margin: 5px 0; }

/* Removed .controls styles as the element is removed */

.schedule-table { width: 100%; border-collapse: collapse; background-color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
.schedule-table th, .schedule-table td { border: 1px solid #ddd; padding: 10px; text-align: left; }
.schedule-table th { background-color: #007bff; color: white; }
.no-schedule-message {
  text-align: center;
  padding: 20px;
  color: #666;
}
.loading-message, .error-message, .no-data-message {
  text-align: center;
  margin-top: 2rem;
  font-size: 1.2rem;
  color: #666;
}

.error-message {
  color: red;
}
</style>
